/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.haipv.gtkhoa501.controller;

import com.haipv.gtkhoa501.util.IObsever;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author PHANHAI
 */
public class TimerManager {

    private Timer timer;
    private TimerTask task;
    private IObsever obsever;
    private final int DELAY = 1000;
    private int current;
    private static TimerManager instance = null;

    private TimerManager() {
    }

    public static TimerManager getInstance() {
        if (instance == null) {
            instance = new TimerManager();
        }
        return instance;
    }

    public void addObsever(IObsever obs) {
        this.obsever = obs;
    }

    public void start(int time) {
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                downTime();
            }
        };
        current = time;
        timer.schedule(task, DELAY, 1000);
    }

    public void stop() {
        timer.cancel();

    }

    private void downTime() {
        --current;
        if (obsever != null) {
            obsever.updateTime(getStringTime(current));
        }
        // System.out.println("Time: " + current);

        if (current == 0) {
            timer.cancel();
            if (obsever != null) {
                obsever.finish();
            }
        }
    }

    public String getCurrent() {
        return getStringTime(current);
    }

    private String getStringTime(int time) {
        String str;
        int mn = time / 60;
        str = (mn > 9) ? "" + mn : "0" + mn;
        mn = time % 60;
        if (mn > 9) {
            str += ":" + mn;
        } else {
            str += ":0" + mn;
        }
        return str;
    }
}
